<script setup>
import { Back } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

import { getCategoryByType } from '@/api/category.js'
import { addSnacks, querySnacksById, editSnacks } from '@/api/snacks.js'
import SelectInput from './components/SelectInput.vue'

import ImgUpload from '@/components/ImgUpload/index.vue'

import { onMounted, watch, ref } from 'vue'
import { ElMessage } from 'element-plus'

const router = useRouter()

const formRef = ref()

const restKey = ref(0)
const textarea = ref('')
const value = ref('')
const imageUrl = ref('')
const actionType = ref('') //添加或修改求情
const snacksList = ref([]) //零食分类列表
const snacksFlavorsData = ref([]) //原始口味数据
const snacksFlavors = ref([]) //待上传口味的数据
const leftSnacksFlavors = ref([]) //下拉框剩余可选择的口味数据
const vueRest = ref('1')
const index = ref(0)
const inputStyle = ref({ flex: 1 })
const ruleForm = ref({
  name: '',
  id: '',
  price: '',
  code: '',
  image: '',
  description: '',
  snacksFlavors: [],
  status: true,
  categoryId: ''
})

const rules = {
  name: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入零食名称'))
        } else {
          const reg = /^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/
          if (!reg.test(value)) {
            callback(new Error('零食名称输入不符，请输入2-20个字符'))
          } else {
            callback()
          }
        }
      },
      trigger: 'blur'
    }
  ],
  categoryId: [{ required: true, message: '请选择零食分类', trigger: 'change' }],
  image: {
    required: true,
    message: '零食图片不能为空'
  },
  price: [
    {
      required: true,
      validator: (rules, value, callback) => {
        const reg = /^([1-9]\d{0,5}|0)(\.\d{1,2})?$/
        if (!reg.test(value) || Number(value) <= 0) {
          callback(new Error('零食价格格式有误，请输入大于零且最多保留两位小数的金额'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  code: [{ required: true, message: '请填写商品码', trigger: 'blur' }]
}

onMounted(() => {
  getSnacksList()
  getFlavorListHand()
  actionType.value = router.currentRoute.value.query.id ? 'update' : 'add'
  if (actionType.value === 'update') {
    getSnacksById()
  }
})

//判断请求是修改时
const getSnacksById = async () => {
  const res = await querySnacksById(router.currentRoute.value.query.id)
  //  console.log(res)
  if (res.data.code === 1) {
    ruleForm.value = res.data.data
    imageUrl.value = ruleForm.value.image
    //  console.log(imageUrl.value )
    // res.data.data.flavors 是一个包含一个对象的数组，该对象具有 id、snacksId、name 和 value 属性。
    //其中，value 属性是一个字符串，包含了口味的数组形式，但它是一个字符串而不是一个数组。
    //因此， value 属性进行解析，将其转换为实际的数组形式。
    snacksFlavors.value = res.data.data.flavors.map(flavor => {
      return {
        id: flavor.id,
        snacksId: flavor.snacksId,
        name: flavor.name,
        value: JSON.parse(flavor.value) // 解析 value 字符串为数组
      }
    })
  }
}

//监听
watch(snacksFlavors, () => {
  getLeftSnacksFlavors()
})

//获取零食分类
const getSnacksList = async () => {
  const res = await getCategoryByType({ type: 1 })
  snacksList.value = res.data.data
}

//过滤已选择的口味下拉框无法再次选择
const getLeftSnacksFlavors = () => {
  let arr = []
  snacksFlavorsData.value.map(item => {
    if (snacksFlavors.value.findIndex(item1 => item.name === item1.name) === -1) {
      arr.push(item)
    }
  })
  leftSnacksFlavors.value = arr
}

// 选择了口味数据
const selectHandle = (val, key, ind) => {
  const arrDate = [...snacksFlavors.value]
  // console.log('选择了：', arrDate)
  const index = snacksFlavorsData.value.findIndex(item => item.name === val)

  arrDate[key] = JSON.parse(JSON.stringify(snacksFlavorsData.value[index]))
  snacksFlavors.value = arrDate
  // console.log('子组件的口味：', arrDate)
}

// 按钮 - 添加口味
const addFlavore = () => {
  snacksFlavors.value.push({ name: '', value: [] })
}

// 按钮 - 删除口味
const delFlavor = name => {
  let ind = snacksFlavors.value.findIndex(item => item.name === name)
  snacksFlavors.value.splice(ind, 1)
}

// 按钮 - 删除口味标签
const delFlavorLabel = (index, ind) => {
  snacksFlavors.value[index].value.splice(ind, 1)
}

//口味位置记录
const flavorPosition = index => {
  index.value = index
}

// 添加口味标签
const keyDownHandle = val => {
  if (event) {
    event.cancelBubble = true
    event.preventDefault()
    event.stopPropagation()
  }
  if (val.target.innerText.trim() != '') {
    snacksFlavors[index].flavorData.push(val.target.innerText)
    val.target.innerText = ''
  }
}

//临时口味
const getFlavorListHand = () => {
  // flavor flavorData
  snacksFlavorsData.value = [
    { name: '包装', value: ['原味', '番茄味', '辣味', '多口味'] },
    { name: '罐装', value: ['原味', '番茄味', '辣味', '多口味'] }
  ]
  leftSnacksFlavors.value = snacksFlavorsData.value
}

//图片地址赋值
const imageChange = value => {
  console.log('图片地址', value)
  imageUrl.value = value
  ruleForm.value.image = imageUrl.value
}

//提交数据
const submitForm = async (formName, st) => {
  console.log(formName, st)
  const valid = await formRef.value.validate()
  if (valid) {
    // console.log('表单验证通过');
    console.log(ruleForm.value) // 提交表单数据
    const params = { ...ruleForm.value }
    params.status = actionType.value === 'add' ? 0 : ruleForm.value.status ? 1 : 0
    params.flavors = snacksFlavors.value.map(obj => ({
      ...obj,
      value: JSON.stringify(obj.value)
    }))

    console.log(params)
    if (actionType.value === 'add') {
      //新增操作
      const res = await addSnacks(params)
      console.log(res)
      if (res.data.code === 1) {
        ElMessage.success('添加零食成功！')
        if (!st) {
          router.push('/snacks')
        } else {
          ruleForm.value = {
            name: '',
            price: '',
            image: '',
            description: '',
            snacksFlavors: [],
            categoryId: ''
          }
        }
      }
    } else {
      //修改
      const res = await editSnacks(params)
      console.log(res)
      if (res.data.code === 1) {
        ElMessage.success('修改成功！')
        router.push('/snacks')
      }
    }
  }
}
</script>

<template>
  <div class="addBrand-container">
    <div style="display: flex; align-items: center;">
      <el-icon style="margin-right: 10px; margin-bottom: 20px">
        <Back />
      </el-icon>
      <el-button type="text" @click="() => router.push('/snacks')" style="margin-bottom: 20px;">返回
      </el-button>

    </div>
    <div class="container">
      <el-form ref="formRef" :model="ruleForm" :rules="rules">
        <div>
          <el-form-item label="零食名称:" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请填写零食名称" maxlength="20" />
          </el-form-item>

          <el-form-item label="零食分类:" prop="categoryId">
            <el-select v-model="ruleForm.categoryId" placeholder="请选择零食分类">
              <el-option v-for="(item, index) in snacksList" :key="index" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>

        </div>
        <el-form-item label="零食价格:" prop="price">
          <el-input v-model="ruleForm.price" placeholder="请设置零食价格" />
        </el-form-item>

        <el-form-item label="口味做法配置:">
          <el-form-item>
            <div class="flavorBox">
              <span v-if="snacksFlavors.length == 0" class="addBut" @click="addFlavore">+ 添加口味</span>
              <div v-if="snacksFlavors.length != 0" class="flavor">
                <div class="title">
                  <span>口味名（3个字内）</span>
                </div>
                <div class="cont">
                  <div v-for="(item, index) in snacksFlavors" :key="index" class="items">
                    <div class="itTit">
                      <SelectInput :snacks-flavors-data="leftSnacksFlavors" :index="index" :value="item.name" @select="selectHandle" />
                    </div>
                    <div class="labItems" style="display: flex">
                      <span v-for="(it, ind) in item.value" :key="ind">{{ it }} <i @click="delFlavorLabel(index, ind)">X</i></span>
                      <div class="inputBox" :style="inputStyle" />
                    </div>
                    <span class="delFlavor delBut non" @click="delFlavor(item.name)">删除</span>
                  </div>
                </div>
                <div v-if="!!leftSnacksFlavors.length && snacksFlavors.length < snacksFlavorsData.length" class="addBut" @click="addFlavore">添加口味</div>
              </div>
            </div>
          </el-form-item>
        </el-form-item>

        <div>
          <el-form-item label="零食图片:" prop="image">
            <ImgUpload :prop-image-url="imageUrl" @imageChange="imageChange">
              图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
            </ImgUpload>

          </el-form-item>
        </div>

        <div class="address">
          <el-form-item label="零食描述:" prop="region">
            <el-input v-model="ruleForm.description" type="textarea" :rows="3" maxlength="200" placeholder="零食描述，最长200字" />
          </el-form-item>
        </div>

        <div class="subBox address">
          <el-button @click="() => router.back()">
            取消
          </el-button>
          <el-button type="primary" :class="{ continue: actionType === 'add' }" @click="submitForm('ruleForm')">
            保存
          </el-button>
          <el-button v-if="actionType == 'add'" type="primary" @click="submitForm('ruleForm', 'goAnd')">
            保存并继续添加
          </el-button>
        </div>

      </el-form>

    </div>
  </div>
</template>


<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 10px;
    margin-top: 10px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      // min-height: 500px;
      .subBox {
        padding-top: 30px;
        text-align: center;
      }

      .address {
        width: 50%;
      }
    }
    .idNumber {
      margin-bottom: 39px;
    }

    .el-form-item {
      margin-bottom: 29px;
    }
    .el-input {
      width: 293px;
    }
  }
}

.flavorBox {
  width: 777px;

  .addBut {
    background: #ffc200;
    display: inline-block;
    padding: 0px 20px;
    border-radius: 3px;
    line-height: 40px;
    cursor: pointer;
    border-radius: 4px;
    color: #333333;
    font-weight: 500;
  }

  .flavor {
    border: solid 1px #dfe2e8;
    border-radius: 3px;
    padding: 15px;
    background: #fafafb;

    .title {
      color: #606168;
      .des-box {
        padding-left: 44px;
      }
    }

    .cont {
      .items {
        display: flex;
        margin: 10px 0;

        .itTit {
          width: 150px;
          margin-right: 15px;

          input {
            width: 100%;
            // line-height: 40px;
            // border-radius: 3px;
            // padding: 0 10px;
          }
        }

        .labItems {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          border-radius: 3px;
          min-height: 39px;
          border: solid 1px #d8dde3;
          background: #fff;
          padding: 0 5px;

          span {
            display: inline-block;
            color: #ffc200;
            margin: 5px;
            line-height: 26px;
            padding: 0 10px;
            background: #fffbf0;
            border: 1px solid #fbe396;
            border-radius: 4px;
            font-size: 12px;

            i {
              cursor: pointer;
              font-style: normal;
            }
          }

          .inputBox {
            display: inline-block;
            width: 100%;
            height: 36px;
            line-height: 36px;
            overflow: hidden;
          }
        }

        .delFlavor {
          display: inline-block;
          padding: 0 10px;
          color: #f19c59;
          cursor: pointer;
        }
      }
    }
  }
}
</style>